import React, { useState, useEffect } from 'react';
import { 
  Form, 
  Input, 
  Button, 
  Select, 
  Card, 
  message,
  Row,
  Col,
  Space,
  Spin,
  Transfer,
  Modal
} from 'antd';
import { 
  SaveOutlined,
  EyeOutlined,
  LinkOutlined,
  FilePdfOutlined
} from '@ant-design/icons';
import { useHistory, useParams } from 'react-router-dom';
// 移除有问题的markdown导入，使用TextArea替代
// PDF导出功能暂时移除，等待兼容性问题解决
import api from '../services/api';

const { Option } = Select;
const { TextArea } = Input;

const CaseEditPage = () => {
  const [loading, setLoading] = useState(false);
  const [fetchLoading, setFetchLoading] = useState(false);
  const [caseData, setCaseData] = useState(null);
  const [solutionMarkdown, setSolutionMarkdown] = useState('');
  const [previewVisible, setPreviewVisible] = useState(false);
  const [resourcesVisible, setResourcesVisible] = useState(false);
  const [allResources, setAllResources] = useState([]);
  const [targetKeys, setTargetKeys] = useState([]);
  const history = useHistory();
  const { id } = useParams();
  const [form] = Form.useForm();

  // 获取案例详情
  const fetchCaseDetail = async () => {
    setFetchLoading(true);
    try {
      const response = await api.get(`/cases/${id}`);
      setCaseData(response.data);
      setSolutionMarkdown(response.data.solution || '');
      
      // 设置表单数据
      form.setFieldsValue({
        title: response.data.title,
        description: response.data.description,
        solution: response.data.solution,
        category: response.data.category,
        keywords: response.data.keywords,
        approved: response.data.approved
      });
    } catch (error) {
      console.error('获取案例详情失败:', error);
      message.error('获取案例详情失败');
    } finally {
      setFetchLoading(false);
    }
  };

  // 获取所有资源
  const fetchAllResources = async () => {
    try {
      const response = await api.get('/resources');
      const resources = response.data || [];
      setAllResources(resources.map(resource => ({
        key: resource.id.toString(),
        title: resource.name,
        description: resource.description || resource.type,
        disabled: false
      })));
      
      // 设置已关联的资源
      const relatedResources = resources.filter(r => r.related_case_id === parseInt(id));
      setTargetKeys(relatedResources.map(r => r.id.toString()));
    } catch (error) {
      console.error('获取资源列表失败:', error);
    }
  };

  useEffect(() => {
    fetchCaseDetail();
  }, [id]);

  const handleSubmit = async (values) => {
    setLoading(true);
    try {
      console.log('提交案例更新数据:', values);
      
      // 更新解决方案为Markdown内容
      const updateData = {
        ...values,
        solution: solutionMarkdown
      };
      
      const response = await api.put(`/cases/${id}`, updateData);
      console.log('案例更新成功:', response.data);
      
      message.success('案例更新成功');
      history.push(`/cases/${id}`);
    } catch (error) {
      console.error('更新案例失败:', error);
      
      if (error.handled) {
        return;
      }
      
      if (error.response) {
        const errorMessage = error.response.data?.detail || '更新案例失败，请稍后重试';
        message.error(errorMessage);
      } else if (error.request) {
        message.error('网络错误，请检查网络连接');
      } else {
        message.error('更新案例失败，请稍后重试');
      }
    } finally {
      setLoading(false);
    }
  };

  // 预览解决方案
  const handlePreview = () => {
    setPreviewVisible(true);
  };

  // 关联资源
  const handleResourcesManage = () => {
    fetchAllResources();
    setResourcesVisible(true);
  };

  // 保存资源关联
  const handleResourcesSave = async () => {
    try {
      setLoading(true);
      
      // 获取当前已关联的资源
      const currentResponse = await api.get('/resources');
      const currentResources = currentResponse.data || [];
      const currentRelated = currentResources.filter(r => r.related_case_id === parseInt(id));
      
      // 取消关联的资源
      for (const resource of currentRelated) {
        if (!targetKeys.includes(resource.id.toString())) {
          await api.put(`/resources/${resource.id}`, {
            ...resource,
            related_case_id: null
          });
        }
      }
      
      // 新关联的资源
      for (const resourceId of targetKeys) {
        const resource = currentResources.find(r => r.id.toString() === resourceId);
        if (resource && resource.related_case_id !== parseInt(id)) {
          await api.put(`/resources/${resourceId}`, {
            ...resource,
            related_case_id: parseInt(id)
          });
        }
      }
      
      message.success('资源关联更新成功');
      setResourcesVisible(false);
    } catch (error) {
      console.error('更新资源关联失败:', error);
      message.error('更新资源关联失败');
    } finally {
      setLoading(false);
    }
  };

  // 导出PDF
  const handleExportPDF = async () => {
    try {
      setLoading(true);
      message.loading('正在生成PDF...', 0);
      
      // 创建一个临时的div用于渲染PDF内容
      const tempDiv = document.createElement('div');
      tempDiv.style.width = '210mm';
      tempDiv.style.padding = '20px';
      tempDiv.style.backgroundColor = 'white';
      tempDiv.style.fontFamily = 'Arial, sans-serif';
      tempDiv.style.fontSize = '14px';
      tempDiv.style.lineHeight = '1.6';
      tempDiv.style.position = 'absolute';
      tempDiv.style.left = '-9999px';
      tempDiv.style.top = '-9999px';
      
      // 构建PDF内容
      tempDiv.innerHTML = `
        <div style="margin-bottom: 30px; border-bottom: 2px solid #1890ff; padding-bottom: 20px;">
          <h1 style="color: #1890ff; margin: 0; font-size: 24px;">${caseData.title}</h1>
          <div style="margin-top: 10px; color: #666;">
            <span>案例ID: ${caseData.id}</span> | 
            <span>分类: ${caseData.category}</span> | 
            <span>状态: ${caseData.approved ? '已审核' : '待审核'}</span>
          </div>
          <div style="margin-top: 5px; color: #666;">
            <span>创建时间: ${new Date(caseData.created_at).toLocaleString()}</span>
          </div>
          ${caseData.keywords ? `<div style="margin-top: 10px;"><strong>关键词:</strong> ${caseData.keywords}</div>` : ''}
        </div>
        
        <div style="margin-bottom: 30px;">
          <h2 style="color: #1890ff; font-size: 18px; margin-bottom: 10px;">问题描述</h2>
          <div style="background: #f5f5f5; padding: 15px; border-radius: 4px; white-space: pre-wrap;">${caseData.description}</div>
        </div>
        
        <div style="margin-bottom: 30px;">
          <h2 style="color: #1890ff; font-size: 18px; margin-bottom: 10px;">解决方案</h2>
          <div style="background: #f9f9f9; padding: 15px; border-radius: 4px;">
            ${solutionMarkdown ? solutionMarkdown.replace(/\n/g, '<br>').replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>').replace(/\*([^*]+)\*/g, '<em>$1</em>') : '暂无解决方案'}
          </div>
        </div>
        
        <div style="margin-top: 40px; text-align: center; color: #999; font-size: 12px; border-top: 1px solid #ddd; padding-top: 20px;">
          <div>导出时间: ${new Date().toLocaleString()}</div>
          <div>Integrated Trouble Tracking System</div>
        </div>
      `;
      
      document.body.appendChild(tempDiv);
      
      // 使用html2canvas转换为图片
      const canvas = await html2canvas(tempDiv, {
        scale: 2,
        useCORS: true,
        backgroundColor: '#ffffff'
      });
      
      // 移除临时div
      document.body.removeChild(tempDiv);
      
      // 创建PDF
      const pdf = new jsPDF('p', 'mm', 'a4');
      const imgWidth = 170; // A4宽度减去边距
      const imgHeight = (canvas.height * imgWidth) / canvas.width;
      
      pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 20, 20, imgWidth, imgHeight);
      
      // 下载PDF
      pdf.save(`案例-${caseData.title}-${new Date().toISOString().split('T')[0]}.pdf`);
      
      message.destroy();
      message.success('PDF导出成功');
    } catch (error) {
      console.error('导出PDF失败:', error);
      message.destroy();
      message.error('导出PDF失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    history.push(`/cases/${id}`);
  };

  if (fetchLoading) {
    return <Spin size="large" style={{ display: 'block', margin: '50px auto' }} />;
  }

  if (!caseData) {
    return <div>案例不存在</div>;
  }

  return (
    <div style={{ maxWidth: '800px', margin: '0 auto' }}>
      <h2>编辑案例</h2>
      
      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Row gutter={16}>
            <Col span={16}>
              <Form.Item
                name="title"
                label="案例标题"
                rules={[{ required: true, message: '请输入案例标题' }]}
              >
                <Input placeholder="请输入案例标题" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="category"
                label="案例分类"
                rules={[{ required: true, message: '请选择案例分类' }]}
              >
                <Select placeholder="选择分类">
                  <Option value="hardware">硬件</Option>
                  <Option value="software">软件</Option>
                  <Option value="firmware">固件</Option>
                  <Option value="network">网络</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={16}>
              <Form.Item
                name="keywords"
                label="关键词"
                extra="多个关键词请用空格分隔"
              >
                <Input placeholder="请输入关键词" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="approved"
                label="审核状态"
              >
                <Select>
                  <Option value={false}>待审核</Option>
                  <Option value={true}>已审核</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="问题描述"
            rules={[{ required: true, message: '请输入问题描述' }]}
          >
            <TextArea 
              rows={4} 
              placeholder="详细描述遇到的问题..."
            />
          </Form.Item>

          <Form.Item
            name="solution"
            label={
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span>解决方案</span>
                <Button 
                  size="small" 
                  icon={<EyeOutlined />} 
                  onClick={handlePreview}
                >
                  预览
                </Button>
              </div>
            }
            rules={[{ required: true, message: '请输入解决方案' }]}
          >
            <div>
              <TextArea
                value={solutionMarkdown}
                onChange={(e) => setSolutionMarkdown(e.target.value)}
                placeholder="请使用Markdown格式编写解决方案...

支持的语法：
# 标题
**粗体** *斜体*
- 列表项
``代码块```
[链接](url)"
                rows={15}
                style={{ 
                  fontFamily: 'Monaco, Menlo, Ubuntu Mono, monospace', 
                  fontSize: '14px',
                  lineHeight: '1.5'
                }}
              />
            </div>
          </Form.Item>

          <Form.Item>
            <Space>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={loading}
                icon={<SaveOutlined />}
              >
                更新案例
              </Button>
              <Button 
                onClick={handleResourcesManage}
                icon={<LinkOutlined />}
              >
                关联资源
              </Button>
              <Button 
                onClick={() => message.info('PDF导出功能暂时不可用，请稍后再试')}
                disabled
                icon={<FilePdfOutlined />}
              >
                导出PDF
              </Button>
              <Button onClick={handleCancel}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      
      {/* 解决方案预览Modal */}
      <Modal
        title="解决方案预览"
        visible={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={[
          <Button key="close" onClick={() => setPreviewVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
        style={{ top: 20 }}
      >
        <div style={{ maxHeight: '60vh', overflow: 'auto' }}>
          <div 
            style={{ 
              padding: 16, 
              whiteSpace: 'pre-wrap',
              fontFamily: 'Arial, sans-serif',
              lineHeight: '1.6'
            }}
            dangerouslySetInnerHTML={{
              __html: (solutionMarkdown || '暂无内容')
                .replace(/\n/g, '<br>')
                .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
                .replace(/\*([^*]+)\*/g, '<em>$1</em>')
                .replace(/^# (.+)$/gm, '<h1 style="color: #1890ff; margin: 16px 0 8px 0;">$1</h1>')
                .replace(/^## (.+)$/gm, '<h2 style="color: #1890ff; margin: 14px 0 6px 0;">$1</h2>')
                .replace(/^- (.+)$/gm, '• $1')
                .replace(/```([^`]+)```/g, '<pre style="background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto;"><code>$1</code></pre>')
            }}
          />
        </div>
      </Modal>
      
      {/* 关联资源Modal */}
      <Modal
        title="管理关联资源"
        visible={resourcesVisible}
        onOk={handleResourcesSave}
        onCancel={() => setResourcesVisible(false)}
        okText="保存关联"
        cancelText="取消"
        confirmLoading={loading}
        width={700}
      >
        <div style={{ margin: '20px 0' }}>
          <Transfer
            dataSource={allResources}
            targetKeys={targetKeys}
            onChange={setTargetKeys}
            render={item => `${item.title} - ${item.description}`}
            titles={['可用资源', '已关联资源']}
            showSearch
            searchPlaceholder="搜索资源"
            style={{ marginBottom: 16 }}
          />
        </div>
      </Modal>
    </div>
  );
};

export default CaseEditPage;